from django.shortcuts import render
from rest_framework.generics import ListAPIView,CreateAPIView,RetrieveAPIView,GenericAPIView
from rest_framework.response import Response
from django.views.generic import View
from .serializers import CategorySerializer,NewsSerializer,FollowedSerializer, GETFollowedSerializer,NewsDetailSerializer,AuthorNewsSerializer,GETCommentSerializer,POSTCommentSerializer,HeadlineSerializer,POSTCategorySerializer
from .models import Category,News,Followed
from rest_framework.permissions import IsAuthenticated
from .paginations import StandardResultsSetPagination
import time
# Create your views here.


class CategoryView(ListAPIView,CreateAPIView):
    """
    查询栏目表
    路由：GET /categories/
    """
    # 指定序列化器
    # serializer_class = CategorySerializer
    pagination_class = None
    # 重写序列化器方法
    def get_serializer_class(self):
        if self.request.method == "GET":
            return CategorySerializer
        else:
            return POSTCategorySerializer
    # 指定查询集
    queryset = Category.objects.filter(is_delete=False)
    # def get(self,request):
    #     """查询栏目分类"""
    #     # 查询参数
    #     # 返回参数
    # def post(self, request, *args, **kwargs):
    # 获取参数
    # 效验参数
    # 保存数据
    # 返回响应


class NewsListView(ListAPIView,CreateAPIView):
    """
    根据分类查询分类对应的新闻
    路由：GET /news?cate=分类的id,当前页数page=当前的页数
    """
    # 指定序列化器
    # serializer_class = NewsSerializer
    pagination_class = None
    # 分页
    # pagination_class = StandardResultsSetPagination
    # 重写序列化器类
    def get_serializer_class(self):

        if self.request.method == "GET":
            return NewsSerializer
        else:
            return HeadlineSerializer

    def get_queryset(self):

        cate = self.request.query_params.get('cate', None)

        print(cate)
        print(type(cate))
        # 指定查询集
        if cate:
            queryset = News.objects.filter(category_id=int(cate)).order_by('-create_time')[0:50]
            print(queryset)
        else:
            queryset = News.objects.all().order_by('-clicks','-create_time')[0:50]
            print("----------")
            print(queryset)

        return queryset
    # def get(self, request, *args, **kwargs):
    #      """展示新闻列表"""
    #
    #      # 调用父类的方法
    #      super().get(self, request, *args, **kwargs)
    # #     # 1.获取分类参数(id)  分页参数(默认为１)
    #     # 2.效验参数
    #     # 3.根据分类ｉｄ查询新闻数据库并按时间排序，且指定加载数量
    #     # 4.序列化返回数据
    # def post(self, request, *args, **kwargs):
    # 获取参数
    # 效验参数
    # 初始化模型 保存数据到数据库
    # 返回响应
    # 指定序列化器
    serializer_class = HeadlineSerializer


class FollowedView(CreateAPIView):
    """关注的视图
    路由:/follows/
    """
    pagination_class = None
    # 配置权限
    # permission_classes = [IsAuthenticated]

    # 指定序列化器
    serializer_class = FollowedSerializer

    # def post(self):
        # 1.获取参数 请求体　user的id news的id
        # 2.效验参数
        # 3.保存关注的记录到数据库
        # 4.返回响应
    def get(self,request):
        """查询该新闻是否被当前用户以关注"""
        # 获取当前用户的用户
        user = self.request.user
        # 查询数据库　查询处当前用户关注的新闻
        try:
            followeds = Followed.objects.filter(user_id = user.id)
        except Exception as e:
            return Response({"messge":"该新闻已关注"})

        time.sleep(3)

        if followeds:
            serializer = GETFollowedSerializer(instance=followeds,many=True)
            # serializer.is_valid(raise_exception=True)
            print(serializer.data)

            return Response(serializer.data)

        return  Response({"messge":"该用户没有关注过新闻"})


class NewsDetailView(RetrieveAPIView):
    """新闻详情的页面
    路由: GET /news/(?P<PK>\d+)
    """
    pagination_class = None
    # 指定序列化器
    serializer_class = NewsDetailSerializer
    # 指定查询集
    # queryset = News.objects.all()
    def get_object(self):
        # 获取命名参数
        pk = self.kwargs.get('pk')
        # 查询出新闻的对象
        # 效验参数
        try:
            news = News.objects.get(pk=pk)
            news.clicks = news.clicks + 1
            news.save()
        except Exception as e:
            return Response({"message":"该新闻不存在"})

        return news
    # def get(self,request,pk):
    # GenericAPIView中的get_object() 会自动根据pk获取查询集中对应的对象
        # 1.获取参数
        # 2.效验参数
        # 3.查询数据库获取新闻的对象
        # 4.序列化对象
        # 5.返回序列化后的对象


class AuthorNewsView(ListAPIView):
    """新闻作者发布的所有新闻的列表
    路由: GET /news/(?P<PK>\d+)/author_news
    """
    pagination_class = None
    # 指定序列化器
    serializer_class = AuthorNewsSerializer

    def get_queryset(self):
        # 获取主键
        pk = self.kwargs.get('pk')
        # 效验参数
        try:
            news = News.objects.get(pk=pk)
        except Exception as e:
            return Response({"message":"该新闻不存在"})

        # 查询处新闻的作者
        user = news.user

        # 查询处当前作者发布的所有新闻
        news_list = user.user_all_new.all()[0:3]

        return news_list

    # def get(self,request,pk):
    #     # 效验参数
    #     try:
    #         news = News.objects.get(pk=pk)
    #     except Exception as e:
    #         return Response({"message":"该新闻不存在"})
    #
    #     # 查询处新闻的作者
    #     user = news.user
    #
    #     # category = news.category
    #     #
    #     # news_list3 = News.objects.filter(category_id=category.id)
    #     # print(news_list3)
    #     #
    #     #
    #     # news_list2 = category.category_all_new.all()
    #     # print(news_list2)
    #     #
    #     # # 查询处当前作者发布的所有新闻
    #     news_list = user.user_all_new.all()[0:3]
    #     print(news_list)
    #
    #     # 序列化数据
    #     serializer = self.get_serializer(news_list,many=True)
    #
    #     # 返回数据
    #     return Response(serializer.data)

    # def get(self,request,pk):
    # GenericAPIView中的get_object() 会自动根据pk获取查询集中对应的对象
        # 1.获取参数
        # 2.效验参数
        # 3.查询数据库获取新闻的对象
        # 4.序列化对象
        # 5.返回序列化后的对象


class CommentView(ListAPIView,CreateAPIView):
    """评论视图类
    路由：news/(?P<pk>\d+)/comments/
    """
    # 根据当前的新闻的主键查询新闻
    # 根据当前的新闻查询处所有的新闻　以及评论的数量
    # 序列化返回
    pagination_class = None
    # 配置权限
    # permission_classes = [IsAuthenticated]
    # 指定序列化器
    def get_serializer_class(self):

        if self.request.method == "GET":
            return GETCommentSerializer
        else:
            return POSTCommentSerializer

    def get_queryset(self):
        # 获取主键
        pk = self.kwargs.get('pk')
        # 查询当前的新闻
        try:
            new = News.objects.get(pk=pk)
        except Exception as e:
            return Response({"message": "该新闻不存在"})

        # 根据新闻查询出评论
        comment = new.comment_set.all().order_by('-create_time')

        return comment

    # def post(self, request, *args, **kwargs):
    #     permission_classes = [IsAuthenticated]
    #     return super().create(request, *args, **kwargs)
    # def post(self, request, *args, **kwargs):
    #     """创建评论"""
        # 1.获取数据
        # 2.效验参数
        # 3.保存数据
        # 4.序列化返回
    # def get(self,request,pk):
    #     # 查询当前的新闻
    #     try:
    #         new = News.objects.get(pk=pk)
    #     except Exception as e:
    #         return Response({"message": "该新闻不存在"})
    #
    #     # 根据新闻查询出评论
    #     comment = new.cooment_set.all()
    #
    #     # 获取序列器返回
    #     serializer = self.get_serializer(comment,many=True)
    #
    #     return Response(serializer.data)


# class HeadlineView(CreateAPIView):
    """提交头条"""

